<?php

namespace app\tools;

use Yii;

class Curl {
  //PHP远程请求相关操作方法

  //get请求
  public static function curl_get($url, $user_agent = '')	{
    $curl = curl_init();
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 3);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($curl, CURLOPT_HEADER, false);
    if ($user_agent) {
      curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);
    }
		curl_setopt($curl, CURLOPT_URL, $url);
		$res = curl_exec($curl);
		curl_close($curl);
		return $res;
  }

  //post请求
  public static function curl_post($url, $data, $user_agent = '', $header='')	{
    $curl = curl_init();
		$method = "POST";
		curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 3);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
		//curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_URL, $url);
    if ($user_agent) {
      $user_agent = "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Mobile Safari/537.36";
      curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);
    }
    if (!empty($header)) {
      curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    }
		$res = curl_exec($curl);
		curl_close($curl);
		return $res;
  }
}
